package com.lry.pda.bottom.c.backend;

import com.lry.pda.bottom.c.backend.type.Symbol;

import java.util.Map;

public class PointerValueSetter implements IValueSetter {
    private Symbol symbol;
    private int index = 0;

    @Override
    public void setValue(Object obj)   {
        int addr = (Integer)symbol.getValue();
        MemoryHeap memHeap = MemoryHeap.getSelf();
        Map.Entry<Integer, byte[]> entry = memHeap.getMem(addr);
        byte[] content = entry.getValue();
        Integer i = (Integer)obj;
        try {
            index = index*symbol.getByteSize();
            if (symbol.getByteSize() == 4) {
                content[index] = (byte)((i>>24) & 0xFF);
                content[index + 1] = (byte)((i>>16) & 0xFF);
                content[index + 2] = (byte)((i>>8) & 0xFF);
                content[index + 3] = (byte)(i & 0xFF);
            } else {
                content[index] = (byte)(i & 0xFF);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }

    public PointerValueSetter(Symbol symbol, int index) {
        this.symbol = symbol;
        this.index = index;
    }
}